/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.institution.approval.ReviseAuditService;
import com.koron.institution.bean.InstitutionFile;
import com.koron.institution.bean.ReviseAssessment;
import com.koron.institution.bean.ReviseAssessmentHistory;
import com.koron.institution.mapper.InstitutionFileMapper;
import com.koron.institution.mapper.ReviseAssessmentHistoryMapper;
import com.koron.institution.mapper.ReviseAssessmentMapper;
import com.koron.institution.service.api.ReviseService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource("classpath:institution.properties")
public class ReviseServiceImpl implements ReviseService, InitializingBean, AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private FlowManagement flowManagement;

//    @Value("${assessment_confirm}")
//    private String assessmentConfirm;
//
//    @Value("${revise_add_template_key}")
//    private String reviseAddTemplateKey;
//
//    @Value("${revise_edit_template_key}")
//    private String reviseEditTemplateKey;
//
//    @Value("${revise_discard_template_key}")
//    private String reviseDiscardTemplateKey;

    @Value("${revise_add_confirm}")
    private String reviseAddConfirm;

    @Value("${revise_edit_confirm}")
    private String reviseEditConfirm;

    @Value("${revise_discard_confirm}")
    private String reviseDiscardConfirm;

    @Value("${supply_corp_code}")
    private String supplyCorpCode;

    @Value("${assessment_revise_template_key}")
    private String assessmentReviseTemplateKey;

    @Value("${assessment_revise_supply_template_key}")
    private String assessmentReviseSupplyTemplateKey;

    @Override
    public MessageBean<?> getReviseList(String corpCode, Integer reviseYear, String institutionName, Integer page, Integer pageSize, Integer state, StaffBean user) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
                return msg;
            }
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ReviseAssessment> list = mapper.selectByCond(corpCode, reviseYear, institutionName, state, start, pageSize, null);
            int total = mapper.selectTotalByCond(corpCode, reviseYear, institutionName, state);
            DataBean<ReviseAssessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getReviseDraftList(String corpCode, Integer reviseYear, String institutionName, Integer page, Integer pageSize, Integer state, StaffBean user) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
                return msg;
            }
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ReviseAssessment> list = mapper.queryDraftList(corpCode, reviseYear, institutionName, start, pageSize);
            int total = mapper.queryDraftListTotal(corpCode, reviseYear, institutionName);
            DataBean<ReviseAssessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> saveOrCommit(StaffBean user, String corpCode, Integer operationType, String reviseAssessmentListStr, String approverCodeListStr, String jobsTaskId, Integer reviseYear) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (null == operationType) {
            msg.setCode(BusinessCode.EMPTY_OPERATION_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_OPERATION_TYPE.getDescription());
            return msg;
        }
        if (null == reviseYear) {
            msg.setCode(BusinessCode.EMPTY_REVISE_YEAR.getCode());
            msg.setDescription(BusinessCode.EMPTY_REVISE_YEAR.getDescription());
            return msg;
        }
        if (1 != operationType && 0 != operationType) {
            msg.setCode(BusinessCode.ILEAGEL_OPERATION_TYPE.getCode());
            msg.setDescription(BusinessCode.ILEAGEL_OPERATION_TYPE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(reviseAssessmentListStr)) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            List<String> approverCodeList = null;
            ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
            List<ReviseAssessment> reviseAssessmentList = JSONObject.parseArray(reviseAssessmentListStr, ReviseAssessment.class);
            //校验
            checkReviseAssessment(corpCode, reviseAssessmentList, msg);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ReviseAssessment reviseAssessment : reviseAssessmentList) {
                //新增评估要判断是否重复评估
                //判断该制度是否已评估修订不能重复添加
                List<ReviseAssessment> reviseAssessments = mapper.queryListByCode(reviseAssessment.getCorpCode(), reviseAssessment.getReviseYear(), reviseAssessment.getInstitutionCode());
                if (reviseAssessments != null && !reviseAssessments.isEmpty() && reviseAssessments.stream().anyMatch(revise -> !revise.getId().equals(reviseAssessment.getId()))) {
                    msg.setCode(24101);
                    msg.setDescription("制度已经存在修订,请勿重复添加!");
                    factory.close(false);
                    return msg;
                }
                if (operationType == 0) {
                    reviseAssessment.setState(5);
                } else {
                    reviseAssessment.setState(1);
                }
                //判断是否新增草稿
                if (StringUtils.isBlank(reviseAssessment.getId())) {
                    //新增草稿
                    BaseEntityUtil.setAddBaseProperties(reviseAssessment, user);
                    mapper.insert(reviseAssessment);
                } else {
                    //修改草稿
                    BaseEntityUtil.setUpdateBaseProperties(reviseAssessment, user);
                    mapper.updateByPrimaryKeySelective(reviseAssessment);
                }
                if (operationType == 1) {
                    //生成历史记录
                    ReviseAssessmentHistory history = new ReviseAssessmentHistory();
                    BeanUtils.copyProperties(reviseAssessment, history);
                    history.setHistoryFlag(0);
                    history.setId(DefaultIdGenerator.getInstance().generateLongId());
                    history.setOldId(reviseAssessment.getId());
                    historyMapper.insert(history);
                    idList.add(history.getId());
                }
            }
            if (operationType == 1) {
                if (StringUtils.isBlank(approverCodeListStr)) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }
                approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
                if (approverCodeList == null || approverCodeList.isEmpty()) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }

                // 构造audit
                Audit audit = new Audit();
                Date now = new Date();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(user.getName());
                audit.setUpdateTime(now);
                audit.setAddUser(user.getName());
                audit.setAddTime(now);
                audit.setFlowType(1);
                audit.setOperation(1);
                audit.setTarget(ReviseAuditService.class.getName());
                audit.setFlowName(reviseAddConfirm);
                audit.setTitle(reviseAddConfirm);
                audit.setCorpCode(corpCode);
                audit.setInitiatorCode(user.getCode());
                audit.setDescription("评审修订提交审批");
                audit.setState(1);
                if (supplyCorpCode.equals(corpCode)) {
                    audit.setTemplateKey(assessmentReviseSupplyTemplateKey);
                } else {
                    audit.setTemplateKey(assessmentReviseTemplateKey);
                }
//                audit.setTemplateKey(reviseAddTemplateKey);
                audit.setBusinessIds(new Gson().toJson(idList));
                //更新任务状态
                if (StringUtils.isNotBlank(jobsTaskId)) {
                    JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                    JobsTasks jobsTasks = jobsTasksMapper.queryById(jobsTaskId);
                    if (jobsTasks != null) {
                        jobsTasks.setBusinessId(new Gson().toJson(idList));
                        Date commitDate = new Date();
                        jobsTasks.setFstatusflag(1);
                        jobsTasks.setState(3);
                        jobsTasks.setCompletedTime(commitDate);
                        jobsTasksMapper.completed(jobsTasks);
                        audit.setOtherBusinessIds(jobsTaskId);
                    }
                }
                Map<String, Object> businessMap = new HashMap<>();
                StringBuilder codes = new StringBuilder();
                for (String code : approverCodeList) {
                    codes.append("1-").append(code.split("_")[0]).append(",");
                }
                businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交评审修订失败");
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("提交评审修订成功");
                }

            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public Map<String, Object> queryExportData(String title, StaffBean user, String corpCode, String corpName, Integer reviseYear) {
        Map<String, Object> map = new HashMap<>();
        try (SessionFactory factory = new SessionFactory()) {
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
            List<ReviseAssessment> list = mapper.selectByCond(corpCode, reviseYear, null, null, null, null, 1);
            map.put("data", list);
            map.put("title", title);
            map.put("corpName", corpName);
            map.put("userName", user == null ? "" : user.getName());
            map.put("makeDate", new Date());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
        return map;
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    ReviseAssessmentHistoryMapper mapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                    List<ReviseAssessmentHistory> list = mapper.queryListByIds(idList);
                    msg.setData(list);
                } else {
                    msg.setCode(BusinessCode.EMPTY_REVISE_ID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_REVISE_ID.getDescription());
                    return msg;
                }
            } else {
                msg.setCode(BusinessCode.EMPTY_REVISE_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_REVISE_ID.getDescription());
                return msg;
            }
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getInstitutionSelect(String corpCode, Integer institutionType, String name, Integer reviseYear) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            ReviseAssessmentMapper reviseAssessmentMapper = factory.getMapper(ReviseAssessmentMapper.class);
            ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(24102);
                msg.setDescription("水司code不能为空");
                return msg;
            }
            List<InstitutionFile> list = mapper.getSelectList(corpCode, institutionType, name);
            List<ReviseAssessment> reviseAssessmentList = reviseAssessmentMapper.queryListByYear(corpCode, reviseYear);
            //去除正在审批中的history的
//            List<ReviseAssessmentHistory> reviseAssessmentHistoryList = historyMapper.queryInProcessList(corpCode, reviseYear);
            if (list != null && !list.isEmpty()) {
                List<InstitutionFile> distinctList = new ArrayList<>();
                for (InstitutionFile institutionFile : list) {
                    if (institutionFile == null) {
                        continue;
                    }
                    if (reviseAssessmentList != null && reviseAssessmentList.stream().anyMatch(reviseAssessment -> {
                        if (reviseAssessment != null) {
                            return institutionFile.getCode().equals(reviseAssessment.getInstitutionCode());
                        } else {
                            return false;
                        }
                    })) {
                        continue;
                    }

                    distinctList.add(institutionFile);
                }
                list = distinctList;
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    MessageBean<?> checkReviseAssessment(String corpCode, List<ReviseAssessment> reviseAssessmentList, MessageBean<?> msg) {

        if (reviseAssessmentList == null || reviseAssessmentList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
            return msg;
        }
        for (ReviseAssessment reviseAssessment : reviseAssessmentList) {
            reviseAssessment.setCorpCode(corpCode);
            if (reviseAssessment == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            if (reviseAssessment.getConformanceFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否符合不能为空");
                return msg;
            }
            if (reviseAssessment.getReviseFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否需要修改不能为空");
                return msg;
            }
            if (reviseAssessment.getReviseYear() == null) {
                msg.setCode(24101);
                msg.setDescription("评估修订年份不能为空");
                return msg;
            }
            if (StringUtils.isBlank(reviseAssessment.getInstitutionCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(reviseAssessment.getCorpCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
                return msg;
            }
        }
        return msg;
    }

    MessageBean<?> checkReviseAssessmentHistory(String corpCode, List<ReviseAssessmentHistory> reviseAssessmentHistoryList, MessageBean<?> msg, boolean isAdd) {

        if (reviseAssessmentHistoryList == null || reviseAssessmentHistoryList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
            return msg;
        }
        for (ReviseAssessmentHistory assessmentHistory : reviseAssessmentHistoryList) {
            assessmentHistory.setCorpCode(corpCode);
            if (assessmentHistory == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            if (!isAdd) {
                if (StringUtils.isBlank(assessmentHistory.getId())) {
                    msg.setCode(24101);
                    msg.setDescription("原评估修订id不能为空");
                    return msg;
                } else {
                    assessmentHistory.setOldId(assessmentHistory.getId());
                }
            }
            if (assessmentHistory.getConformanceFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否符合不能为空");
                return msg;
            }
            if (assessmentHistory.getReviseFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否需要修改不能为空");
                return msg;
            }
            if (assessmentHistory.getReviseYear() == null) {
                msg.setCode(24101);
                msg.setDescription("评估修订年份不能为空");
                return msg;
            }
            if (StringUtils.isBlank(assessmentHistory.getInstitutionCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(assessmentHistory.getCorpCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
                return msg;
            }
        }
        return msg;
    }

    MessageBean<?> checkDiscardReviseAssessmentHistory(List<ReviseAssessmentHistory> reviseAssessmentHistoryList, MessageBean<?> msg) {

        if (reviseAssessmentHistoryList == null || reviseAssessmentHistoryList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
            return msg;
        }
        for (ReviseAssessmentHistory assessmentHistory : reviseAssessmentHistoryList) {
            if (assessmentHistory == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(assessmentHistory.getId())) {
                msg.setCode(24101);
                msg.setDescription("原评估修订id不能为空");
                return msg;
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> batchEdit(StaffBean user, String corpCode, String reviseAssessmentHistoryListStr, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            Date now = new Date();
            List<String> approverCodeList = null;
            ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);

            if (StringUtils.isBlank(reviseAssessmentHistoryListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            List<ReviseAssessmentHistory> reviseAssessmentHistoryList = JSONObject.parseArray(reviseAssessmentHistoryListStr, ReviseAssessmentHistory.class);

            //校验
            checkReviseAssessmentHistory(corpCode, reviseAssessmentHistoryList, msg, false);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ReviseAssessmentHistory reviseAssessmentHistory : reviseAssessmentHistoryList) {
                //修改原记录状态为审核中
                ReviseAssessment assessment = mapper.selectByPrimaryKey(reviseAssessmentHistory.getOldId());
                if (assessment == null) {
                    msg.setCode(BusinessCode.OLD_RECORD_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.OLD_RECORD_NOT_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                reviseAssessmentHistory.setState(2);
                reviseAssessmentHistory.setAddTime(assessment.getAddTime());
                reviseAssessmentHistory.setAddUser(assessment.getAddUser());
                reviseAssessmentHistory.setAddUserName(assessment.getAddUserName());
                reviseAssessmentHistory.setId(DefaultIdGenerator.getInstance().generateLongId());
                BaseEntityUtil.setUpdateBaseProperties(reviseAssessmentHistory, user);
                historyMapper.insert(reviseAssessmentHistory);

                assessment.setState(2);
                mapper.updateByPrimaryKeySelective(assessment);
                idList.add(reviseAssessmentHistory.getId());
            }

            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            // 构造audit
            Audit audit = new Audit();

            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(ReviseServiceImpl.class.getName());
            audit.setFlowName(reviseEditConfirm);
            audit.setTitle(reviseEditConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("编辑评审修订提交审批");
            audit.setState(1);
            if (supplyCorpCode.equals(corpCode)) {
                audit.setTemplateKey(assessmentReviseSupplyTemplateKey);
            } else {
                audit.setTemplateKey(assessmentReviseTemplateKey);
            }
//            audit.setTemplateKey(reviseEditTemplateKey);
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("编辑提交评审修订失败");
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("编辑提交评审修订成功");
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> batchDiscard(StaffBean user, String corpCode, String reviseAssessmentHistoryListStr, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            List<String> approverCodeList = null;
            ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);

            if (StringUtils.isBlank(reviseAssessmentHistoryListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT.getDescription());
                return msg;
            }
            List<ReviseAssessmentHistory> reviseAssessmentHistoryList = JSONObject.parseArray(reviseAssessmentHistoryListStr, ReviseAssessmentHistory.class);
            //校验
//            checkReviseAssessmentHistory(corpCode, reviseAssessmentHistoryList, msg, false);
            checkDiscardReviseAssessmentHistory(reviseAssessmentHistoryList, msg);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ReviseAssessmentHistory reviseAssessmentHistory : reviseAssessmentHistoryList) {
                ReviseAssessment assessment = mapper.selectByPrimaryKey(reviseAssessmentHistory.getId());
                if (assessment == null) {
                    msg.setCode(BusinessCode.OLD_RECORD_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.OLD_RECORD_NOT_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                BeanUtils.copyProperties(assessment, reviseAssessmentHistory);
                reviseAssessmentHistory.setState(3);
                reviseAssessmentHistory.setId(DefaultIdGenerator.getInstance().generateLongId());
                reviseAssessmentHistory.setOldId(assessment.getId());
                BaseEntityUtil.setUpdateBaseProperties(reviseAssessmentHistory, user);
                historyMapper.insert(reviseAssessmentHistory);
                //修改原记录状态为审核中

                assessment.setState(3);
                mapper.updateByPrimaryKeySelective(assessment);
                idList.add(reviseAssessmentHistory.getId());
            }

            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(2);
            audit.setTarget(ReviseServiceImpl.class.getName());
            audit.setFlowName(reviseDiscardConfirm);
            audit.setTitle(reviseDiscardConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("废除评审修订提交审批");
            audit.setState(1);
            if (supplyCorpCode.equals(corpCode)) {
                audit.setTemplateKey(assessmentReviseSupplyTemplateKey);
            } else {
                audit.setTemplateKey(assessmentReviseTemplateKey);
            }
//            audit.setTemplateKey(reviseDiscardTemplateKey);
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("废除提交评审修订失败");
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("废除提交评审修订成功");
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> deleteDraft(String reviseAssessmentId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);

            if (StringUtils.isBlank(reviseAssessmentId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            ReviseAssessment reviseAssessment = mapper.selectByPrimaryKey(reviseAssessmentId);
            if (reviseAssessment == null) {
                msg.setCode(BusinessCode.ASSESSMENT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_NOT_EXIST.getDescription());
                return msg;
            } else if (reviseAssessment.getState() != 5) {
                msg.setCode(BusinessCode.REVISE_CAN_NOT_DELETE.getCode());
                msg.setDescription(BusinessCode.REVISE_CAN_NOT_DELETE.getDescription());
                return msg;
            }
            mapper.deleteByPrimaryKey(reviseAssessmentId);
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> getReviseHistoryListByIds(String businessIds) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
//            ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
            if (StringUtils.isBlank(businessIds)) {
                msg.setCode(24000);
                msg.setDescription("业务id不能为空");
                return msg;
            }
            List<String> businessIdList = JSONObject.parseArray(businessIds, String.class);
            if (businessIdList != null && !businessIdList.isEmpty()) {
//                List<ReviseAssessment> list = mapper.queryListByIds(businessIdList);
//                msg.setData(list);
                ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                List<ReviseAssessmentHistory> list = historyMapper.queryListByIds(businessIdList);
                msg.setData(list);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(ReviseServiceImpl.class.getName(), this);
        map.put(ReviseAuditService.class.getName(), new ReviseAuditService());
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ReviseAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            ReviseAssessment reviseAssessment = translate(history);
                            //这里未保存历史记录 仅保存了审批记录
                            //若需要生成历史记录需要新建历史,不能直接覆盖原审批记录,否则 审批流程查看时数据会变
                            reviseAssessment.setId(history.getOldId());
                            reviseAssessment.setState(0);
                            mapper.updateByPrimaryKeySelective(reviseAssessment);
                            history.setState(0);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private void editApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ReviseAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            ReviseAssessment reviseAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if (reviseAssessment != null) {
                                reviseAssessment.setState(0);
                                mapper.updateByPrimaryKeySelective(reviseAssessment);
                            }
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ReviseAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            //这里只当作审批记录 若需要历史记录只需将将历史状态改为1即可
                            history.setState(0);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            mapper.deleteByPrimaryKey(history.getOldId());
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private void discardApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                ReviseAssessmentHistoryMapper historyMapper = factory.getMapper(ReviseAssessmentHistoryMapper.class);
                ReviseAssessmentMapper mapper = factory.getMapper(ReviseAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ReviseAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            ReviseAssessment reviseAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if (reviseAssessment != null) {
                                reviseAssessment.setState(0);
                                mapper.updateByPrimaryKeySelective(reviseAssessment);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (audit.getOperation() == 1) {
                editApprovalDiscard(idList);
            } else if (audit.getOperation() == 2) {
                discardApprovalDiscard(idList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    private static ReviseAssessment translate(ReviseAssessmentHistory history) {
        ReviseAssessment reviseAssessment = new ReviseAssessment();
        reviseAssessment.setCorpCode(history.getCorpCode());
        reviseAssessment.setReviseYear(history.getReviseYear());
        reviseAssessment.setInstitutionType(history.getInstitutionType());
        reviseAssessment.setInstitutionId(history.getInstitutionId());
        reviseAssessment.setInstitutionCode(history.getInstitutionCode());
        reviseAssessment.setInstitutionFileCode(history.getInstitutionFileCode());
        reviseAssessment.setInstitutionFileName(history.getInstitutionFileName());
        reviseAssessment.setPublicationDate(history.getPublicationDate());
        reviseAssessment.setExecutionDate(history.getExecutionDate());
        reviseAssessment.setApplicableProvisions(history.getApplicableProvisions());
        reviseAssessment.setRemark(history.getRemark());
        reviseAssessment.setVersion(history.getVersion());
        reviseAssessment.setAttachment(history.getAttachment());
        reviseAssessment.setConformanceFlag(history.getConformanceFlag());
        reviseAssessment.setExecuteState(history.getExecuteState());
        reviseAssessment.setProblems(history.getProblems());
        reviseAssessment.setReviseFlag(history.getReviseFlag());
        reviseAssessment.setReviseRemark(history.getReviseRemark());
        reviseAssessment.setAddUser(history.getAddUser());
        reviseAssessment.setUpdateUser(history.getUpdateUser());
        reviseAssessment.setAddTime(history.getAddTime());
        reviseAssessment.setUpdateTime(history.getUpdateTime());
        reviseAssessment.setAddUserName(history.getAddUserName());
        reviseAssessment.setUpdateUserName(history.getUpdateUserName());
        return reviseAssessment;
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
